package com.zyy.java8.samples.stream;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * @author zhangyiying
 * @ClassName: Optional2
 * @Description: Examples how to avoid null checks with Optional:
 * @date 2021/12/27 14:18
 */
public class Optional2 {

    static class Outer {
        Nested nested = new Nested();

        public Nested getNested() {
            return nested;
        }
    }

    static class Nested {
        Inner inner = new Inner();

        public Inner getInner() {
            return inner;
        }
    }

    static class Inner {
        String foo = "foo";

        public String getFoo() {
            return foo;
        }
    }

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }


    public static <T> Optional<T> resolve(Supplier<T> resolve) {
        try {
            T result = resolve.get();
            return Optional.ofNullable(result);
        } catch (NullPointerException e) {
            return Optional.empty();
        }

    }

    private static void test3() {
        Outer outer = new Outer();

        resolve(() -> outer.getNested().getInner().getFoo())
                .ifPresent(System.out::println);
    }

    /**
     * flatMap(Function mapper): 与map类似。返回值是Optional
     */
    private static void test2() {
        Optional.of(new Outer())
                .map(Outer::getNested)
                .map(Nested::getInner)
                .map(Inner::getFoo)
                .ifPresent(System.out::println);
    }

    /**
     * map(Function f): 如果有值对其处理，并返回处理后的Optional，否则返回Optional.empty();
     */
    private static void test1() {
        Optional.of(new Outer())
                .flatMap(outer -> Optional.ofNullable(outer.nested))
                .flatMap(nested -> Optional.ofNullable(nested.inner))
                .flatMap(inner -> Optional.ofNullable(inner.foo))
                .ifPresent(System.out::println);
    }
}
